package com.qing.thread.deadlock;

/**
 * 死锁
 */
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup("小丽",1);
        Makeup g2 = new Makeup("小红",2);

        new Thread(g1).start();
        new Thread(g2).start();
    }
}
//梳子
class Comb{}
//镜子
class Mirror{}

//化妆
class Makeup implements Runnable{
    //因为线程要访问的资源是同一个，所以static确保对象只有一个
    static Comb comb = new Comb();
    static Mirror mirror = new Mirror();

    //女孩姓名
    String girlName;
    //女孩选择
    int choose;

    public Makeup(String girlName,int choose){
        this.girlName = girlName;
        this.choose = choose;
    }

    @Override
    public void run() {
        try {
            makeUp();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    //化妆方法
    public void makeUp() throws InterruptedException {
        if(choose == 1){
            synchronized (comb){
                System.out.println(girlName+"拿到了梳子");
                Thread.sleep(1000);
            }
            synchronized (mirror){
                System.out.println(girlName+"拿到了镜子");
            }
        }else{
            synchronized (mirror){
                System.out.println(girlName+"拿到了镜子");
                Thread.sleep(2000);
            }
            synchronized (comb){
                System.out.println(girlName+"拿到了梳子");
            }
        }
    }
}